package com.heima;

import org.apache.kafka.clients.consumer.*;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;

public class ConsumerDemo {
    public static void main(String[] args) throws InterruptedException {
        Logger.getLogger("org.apache.spark").setLevel(org.apache.log4j.Level.INFO);
        Logger.getLogger("org.eclipse.jetty.server").setLevel(Level.OFF);
        //2.封装kafka相关信息 到集合中
        Properties config = new Properties();
        //3.指定kafka地址,setProperty只接受string类型的数据
        config.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.225.128:9092,192.168.225.128:9192");
        //4.指定key和value的反序列化器
        config.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
        config.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
        //5.设置消费者所属组
        config.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "group1");
        //1.创建消费者对象，kafka 中消息格式key value格式
        Consumer<String, String> consumer = new KafkaConsumer<String, String>(config);
        //6.订阅主题
        consumer.subscribe(Arrays.asList("TopicSource"));
        //7.拉取消息，如果主题中没有消息，等待五秒后拉取
        while (true) {
            ConsumerRecords<String, String> consumerRecords = consumer.poll(Duration.ofSeconds(5));
            //8.遍历拿到的消息
            Thread.sleep(10000);
            System.out.println("获取到了生产者的消息，正在解析中.....");
            for (ConsumerRecord<String, String> consumerRecord : consumerRecords) {
                System.out.println("获取到主题中的建为：" + consumerRecord.key());
                System.out.println("获取到主题中的值为：" + consumerRecord.value());
            }
        }
    }
}
